package com.lightsh.livewallpaper;

import java.io.File;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

public class MyLiveWallpaperService extends WallpaperService{
	
	private static final boolean DEBUG = false;
	private static final String TAG = "MyLiveWallpaperService";
	
	private static final String PATH_OF_PICTURE = "/sdcard/photo/wallpaper";

	@Override
	public Engine onCreateEngine() {
		return new MyWallpaperEngine();
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	private class MyWallpaperEngine extends Engine implements SensorEventListener {
		
		private boolean mbVisible = false;
		private int mPictureIndex = -1;
		
		private long mLastShakeChange = 0;
		private float mLastX = 0;
		private float mLastY = 0;
		private float mLastZ = 0;
		
		private final static int SHAKE_CHECK_INTERVAL = 100;
		private final static int SHAKE_THRESHOLD = 2000;
		
		private final static int SHAKE_TO_DRAW_INTERVAL = 1000;
		private long mLastDrawTime = 0;
		
		private static final int DRAW_TYPE_NEXT = 0;
		private static final int DRAW_TYPE_PREVIOUS = 1;
		
		@Override
		public Bundle onCommand(String action, int x, int y, int z,
				Bundle extras, boolean resultRequested) {
			// 收到2种事件:点击事件(点击位置没有移动才会收到); 桌面图标被放下
//			if(DEBUG){
//				Log.e(TAG, "onCommand:" + action);
//			}
			if("android.wallpaper.tap".equals(action)){
				drawNextPicture(DRAW_TYPE_NEXT);
				// 一个点击事件
				//Toast.makeText(MyLiveWallpaperService.this, "点击了一下", Toast.LENGTH_SHORT).show();
			}else{
				if("android.home.drop".equals(action)){
					// 图标被放下
					//Toast.makeText(MyLiveWallpaperService.this, "图标放下", Toast.LENGTH_SHORT).show();
				}
			}
			return super.onCommand(action, x, y, z, extras, resultRequested);
		}

		@Override
		public void onCreate(SurfaceHolder surfaceHolder) {
			super.onCreate(surfaceHolder);
			setTouchEventsEnabled(true);
			
			// 注册传感器
			SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
			
			sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
		}

		@Override
		public void onDestroy() {
			super.onDestroy();
			
			SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
			sm.unregisterListener(this);
			
		}

		@Override
		public void onSurfaceCreated(SurfaceHolder holder) {
			if(DEBUG){
				Log.e(TAG, "onSurfaceCreated");
			}
			super.onSurfaceCreated(holder);
			drawNextPicture(DRAW_TYPE_NEXT);
		}

		@Override
		public void onSurfaceDestroyed(SurfaceHolder holder) {
			if(DEBUG){
				Log.e(TAG, "onSurfaceDestroyed");
			}
			super.onSurfaceDestroyed(holder);
		}

		@Override
		public void onTouchEvent(MotionEvent event) {
//			if(DEBUG){
//				Log.e(TAG, "onTouchEvent:" + event);
//			}
			// 这里会收到 按下/ 持续按着(如果手不离开，会不断收到) / 弹起 3个点击事件。
			super.onTouchEvent(event);
		}

		@Override
		public void onVisibilityChanged(boolean visible) {
			// 当桌面被其他窗口遮住/再次返回桌面时会产生该消息
			mbVisible = visible;
			super.onVisibilityChanged(visible);
		}
		
		
		
		@Override
		public void onOffsetsChanged(float xOffset, float yOffset,
				float xOffsetStep, float yOffsetStep, int xPixelOffset,
				int yPixelOffset) {
//			if(DEBUG){
//				Log.e(TAG, "onOffsetsChanged");
//			}
			// 当左面切换到另一个页面时会产生该消息
			super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep,
					xPixelOffset, yPixelOffset);
		}

		// 绘制图片
		private void drawNextPicture(int type){
			SurfaceHolder holder = getSurfaceHolder();
			Canvas canvas = holder.lockCanvas();
			if(canvas != null){
				boolean bDraw = false;
				File file = new File(PATH_OF_PICTURE);
				if(file.exists() && file.isDirectory()){
					File[] fileArray = file.listFiles();
					if(fileArray.length > 0){
						// 是否已经从其中一头返回到另一头
						boolean bEndWithNotFile = false;
						
						if(type == DRAW_TYPE_NEXT){
							if(mPictureIndex >= fileArray.length -1 || mPictureIndex < -1){
								// 如果当前时末尾图片，则返回
								mPictureIndex = -1;
							}
							for (int i = mPictureIndex + 1; i < fileArray.length; ++i) {
								if (fileArray[i].isFile()) {
									Bitmap bm = BitmapFactory.decodeFile(fileArray[i].getAbsolutePath());
									if (bm != null) {
										mPictureIndex = i;
										canvas.drawBitmap(bm, new Rect(0, 0, bm.getWidth(), bm.getHeight()),
												new Rect(0, 0, canvas
														.getWidth(), canvas
														.getHeight()), null);
										bDraw = true;
										if(DEBUG){
											Log.e(TAG, "next:" + mPictureIndex);
										}
										break;
									}
								}
								// 到这里表示没有加载到图片,可能是非图片或者目录的原因
								if (i == fileArray.length - 1) {
									if (!bEndWithNotFile) {
										// 允许一次从0开始查找
										bEndWithNotFile = true;
										i = 0;
									}
								}
							}
						}else{
							if(type == DRAW_TYPE_PREVIOUS){
								// 上一张
								if(mPictureIndex > fileArray.length || mPictureIndex <= 0){
									// 如果当前时末尾图片，则返回
									mPictureIndex = fileArray.length;
								}
								for(int i = mPictureIndex - 1; i >= 0; --i){
									if(fileArray[i].isFile()){
										Bitmap bm = BitmapFactory.decodeFile(fileArray[i].getAbsolutePath());
										if(bm != null){
											mPictureIndex = i;
											canvas.drawBitmap(bm, new Rect(0, 0, bm.getWidth(), bm.getHeight()), new Rect(0, 0, canvas.getWidth(), canvas.getHeight()), null);
											bDraw = true;
											if(DEBUG){
												Log.e(TAG, "previous:" + mPictureIndex);
											}
											break;
										}
									}
									// 到这里表示没有加载到图片,可能是非图片或者目录的原因
									if(i == 0){
										if(!bEndWithNotFile){
											// 允许一次从末尾开始查找
											bEndWithNotFile = true;
											i = fileArray.length - 1;
										}
									}
								}
							}
							
						}
							
					}
				}
				if(!bDraw){
					if(DEBUG){
						Log.e(TAG, "can't find picture to draw");
					}
					//canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon), canvas.getWidth()/2,canvas.getHeight() /2, null);
				}
				holder.unlockCanvasAndPost(canvas);
			}
		}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
//			if(DEBUG){
//				Log.e(TAG, "onAccuracyChanged:" + sensor + ";" + accuracy);
//			}
			
		}

		public void onSensorChanged(SensorEvent event) {
			if(mbVisible){
//				if(Math.abs(event.values[SensorManager.DATA_X]) > 18){
//					Log.e(TAG, String.valueOf(event.values[SensorManager.DATA_X]));
//				}
				long curTime = System.currentTimeMillis();
				// 每100毫秒检测一次
				if ((curTime - mLastShakeChange) > SHAKE_CHECK_INTERVAL) {
					long diffTime = (curTime - mLastShakeChange);
					mLastShakeChange = curTime;
					
					float x = event.values[SensorManager.DATA_X];
					float y = event.values[SensorManager.DATA_Y];
					float z = event.values[SensorManager.DATA_Z];

					float speed = Math.abs(x + y + z - mLastX - mLastY - mLastZ) / diffTime * 10000;

					if (speed > SHAKE_THRESHOLD) {
						if(curTime - mLastDrawTime > SHAKE_TO_DRAW_INTERVAL){
							if(DEBUG){
								Log.e(TAG, "shake speed:" + speed + ", x:" + x);
							}
							mLastDrawTime = curTime;
							Vibrator vb = (Vibrator)getSystemService(VIBRATOR_SERVICE);
					    	vb.vibrate(100);
							// 绘制令一张图片
					    	if(x > 0){
					    		// 上一张
					    		drawNextPicture(DRAW_TYPE_PREVIOUS);
					    	}else{
					    		// 下一张
					    		drawNextPicture(DRAW_TYPE_NEXT);
					    	}
						}else{
							if(DEBUG){
								Log.e(TAG, "shake too fast, drop it");
							}							
						}
						
					}
					mLastX = x;
					mLastY = y;
					mLastZ = z;
				}
			
			
			
			}
		}
	}
	
}
